/**
 * 以下9个转化方法都已验证
 */

// 异步方法
export const fileToBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      resolve(e.target.result);
    };
    reader.onerror = err => {
      reject(err);
    };
    // 返回 base64 格式
    reader.readAsDataURL(file?.raw || file);
  });
};

// 异步方法
export const fileToBlob = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      let blob;
      if (typeof e.target.result === 'object') {
        blob = new Blob([e.target.result]);
      } else {
        blob = e.target.result;
      }
      resolve(blob);
    };
    reader.onerror = err => {
      reject(err);
    };
    // 返回 blob 格式
    reader.readAsArrayBuffer(file?.raw || file);
  });
};

export const base64ToFile = (base64Url, fileName) => {
  const pureBase64 = base64Url.startsWith('data')
    ? base64Url.split(',')[1]
    : base64Url;
  let bstr = atob(pureBase64);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  let file = new File([u8arr], fileName, {
    type: `image/${fileName.split('.')[1]}`
  });
  return file;
};

export const base64ToBlob = (base64String, miniType = 'image/jpeg') => {
  const pureBase64 = base64String.startsWith('data')
    ? base64String.split(',')[1]
    : base64String;
  const decodedString = atob(pureBase64);
  const byteArray = new Uint8Array(decodedString.length);
  for (let i = 0; i < decodedString.length; i++) {
    byteArray[i] = decodedString.charCodeAt(i) & 0xff;
  }
  return new Blob([byteArray], { type: miniType });
};

export const blobToFile = (blob, filename, filetype) => {
  return new File([blob], filename, filetype);
};

// 异步方法
export const blobToBase64 = blob => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      resolve(e.target.result);
    };
    reader.onerror = err => {
      reject(err);
    };
    reader.readAsDataURL(blob);
  });
};

// 异步方法
export const fileToUrl = file => {
  return new Promise((resolve, reject) => {
    fileToBlob(file)
      .then(res => {
        resolve(blobToUrl(res));
      })
      .catch(err => {
        reject(err);
      });
  });
};

export const base64ToUrl = (base64String, miniType = 'image/jpeg') => {
  let blob = base64ToBlob(base64String, miniType);
  // 返回路径格式
  return URL.createObjectURL(blob);
};

export const blobToUrl = blob => {
  // 返回路径格式
  return URL.createObjectURL(blob);
};
